<template>
    <div class="app-container">

        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-radio-group v-model="radio">
              <el-radio-button :label="1">机构</el-radio-button>
              <el-radio-button :label="2">农户</el-radio-button>
            </el-radio-group>
            <el-form-item label="年度" prop="planY">
              <el-date-picker
                v-model="queryParams.planY"
                type="year"
                format="yyyy"
                value-format="yyyy"
                placeholder="选择种植年度">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="水管机构" prop="orgCd" width="50px">
              <treeselect
                v-model="queryParams.orgCd"
                :options="xzqhOptions"
                :disable-branch-nodes="true"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="水管机构"
                @select="selectAd"
              />
            </el-form-item>
            <el-form-item v-if="radio == 2" label="农户" prop="farmCd">
              <el-select v-model="queryParams.farmCd">
                    <el-option
                        v-for="item in WiFarmerBList"
                        :key="item.farmCd"
                        :label="item.farmNm"
                        :value="item.farmCd"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <!-- <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['waterDistribution:wrPlanDayRiun:export']"
                >导出</el-button> -->
            </el-form-item>
        </el-form>

        <!-- <div class="tb_left" >年度限额总指标：<span class="hj_cl_blue">48837m³</span></div> -->
        <div class="tb_title" >{{tableTitle?tableTitle:''}}用水过程管理</div>
        <div class="tb_dw" >定额总水量：<span class="hj_cl_blue">{{sumPlan}}万m³</span></div>
        <el-table border v-loading="aloading" height="250" :data="wrPlanDayAdList" :header-cell-style="tableHeaderColor">
            <el-table-column label="地块名称" min-width="180" align="left" prop="landNm" show-overflow-tooltip/>
            <el-table-column label="土地性质"  align="center" prop="landAttr" show-overflow-tooltip>
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.land_attr" :value="scope.row.landAttr"/>
                </template>
            </el-table-column>
            <el-table-column label="作物"  align="center" prop="cropNm" show-overflow-tooltip/>
            <el-table-column label="面积（亩）"  align="center" prop="landSize" />
            <el-table-column label="定额水量（m³）" align="center" prop="planVol" show-overflow-tooltip/>
        </el-table>
        <div class="tb_title" style="margin-top:20px">{{tableTitle?tableTitle:''}}计划用水过程</div>
        <el-table border v-loading="loading"  :data="wrPlanRiunList" :header-cell-style="tableHeaderColor">
            <el-table-column label="月份"  align="center" prop="planYm" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.planYm">{{  scope.row.planYm.substr(4,6) + '月' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上旬"  align="center" prop="firstCtrl" show-overflow-tooltip>
              <el-table-column label="定额"  align="center" prop="firstCtrl" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="计划"  align="center" prop="firstPlan" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="!scope.row.xEdit">{{ scope.row.firstPlan == '0.00'?'':scope.row.firstPlan }}</span>
                  <el-input v-show="scope.row.xEdit" size="mini" v-model="scope.row.firstPlan"></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="中旬"  align="center" prop="senTen" >
              <el-table-column label="定额"  align="center" prop="secondCtrl" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="计划"  align="center" prop="secondPlan" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="!scope.row.xEdit">{{ scope.row.secondPlan == '0.00'?'':scope.row.secondPlan }}</span>
                  <el-input v-show="scope.row.xEdit" size="mini" v-model="scope.row.secondPlan"></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="下旬" align="center" prop="thiTen" show-overflow-tooltip>
              <el-table-column label="定额"  align="center" prop="thirdCtrl" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="计划"  align="center" prop="thirdPlan" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="!scope.row.xEdit">{{ scope.row.thirdPlan == '0.00'?'':scope.row.thirdPlan }}</span>
                  <el-input v-show="scope.row.xEdit" size="mini" v-model="scope.row.thirdPlan"></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="月水量" align="center" prop="monSum" show-overflow-tooltip>
              <el-table-column label="定额"  align="center" prop="monCtrl" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="计划"  align="center" prop="monPlan" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span >{{ parseFloat(scope.row.firstPlan)  + parseFloat(scope.row.secondPlan) +  parseFloat(scope.row.thirdPlan)}}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px" >
                <template slot-scope="scope">
                    <el-button v-show="!scope.row.xEdit&&scope.$index!=11" size="mini" type="text" icon="el-icon-edit"  @click="handleUpdate(scope.$index, scope.row)"
                    >编辑</el-button>
                    <el-button v-show="scope.row.xEdit&&scope.$index!=11" size="mini" type="text"  @click="handlesave(scope.$index, scope.row)"
                    >保存</el-button>
                    <el-button v-show="scope.row.xEdit&&scope.$index!=11" size="mini" type="text"  @click="handleQuit(scope.$index, scope.row)"
                    >撤销</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin:20px">
            <el-button type="primary"  size="mini" @click="handleClick(1)">导入上年数据</el-button>
            <el-button type="primary"  size="mini" @click="handleClick(2)">重新汇总</el-button>
        </el-row>
    </div>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { listWiFarmerB} from "@/api/datam/WiFarmerB";

  import { organtreeList } from "@/api/common";
  import { getAcrePlanByYear,getWiLandBListByFarmCd,listWiOrgplanM,listWiFarmplanM,OrgcalcTenPlan,updateWiOrgplanM,importLastYearOrgPlan,importLastYearFarmPlan} from "@/api/waterDistribution/wrPlanManage";
  export default {
    name: "WrPlanDayAd",
    components: { Treeselect },
    dicts: ["land_attr"],
    data() {
      return {
        // 遮罩层
        loading: true,
        aloading:true,
        // 选中数组
        ids: [],
        radio:1,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        rowSpanArrYear: [],
        rowSpanArrQuarter: [],
        rowSpanArrMonth: [],
        positionYear: 0,
        positionQuarter: 0,
        positionMonth: 0,
        // 行政区用水日计划表格数据
        wrPlanDayAdList: [],
        wrPlanRiunList:[],
        // 行政区划树选项
        xzqhOptions: [],
        // 表头行政区划名称数组
        tableLabel: [],
        // 弹出层标题
        // title: "",
        // 列表标题行内容
        tableTitle: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 70,
          planY: null,
          orgCd: "ORG6543220000",
          tableTitle: '赛尔江西路居委会'
        },
        // 合计统计
        sums: [],
        showSum: false,
        myheight: 600,
        sumPlan:''
      };
    },
    computed:{
      titleStr(){
        let str = ''
        str = this.queryParams.planY + '年' + this.queryParams.tableTitle
        if(this.radio == 2){
          str+= this.WiFarmerBList.filter(item => {return item.farmCd == this.queryParams.farmCd})[0].farmNm
        }
        return str
      }
    },
    created() {
      let day = new Date();
      let nowYear = day.getFullYear().toString();
      this.queryParams.planY = nowYear;
      this.getTreeselect();
      this.getlistWiFarmer();
      this.getList();
    },
    mounted() {

    },
    methods: {
      /** 修改table header的背景色 */
      tableHeaderColor(row, rowIndex) {
        return 'background-color: #e6f4f8; font-weight: 700px !important;';
      },
      // 获取区划名称
      selectAd(val) {
        this.queryParams.tableTitle = val.orgNm
        this.getlistWiFarmer()
      },
      /** 查询农户信息登记列表 */
      getlistWiFarmer() {
        listWiFarmerB({orgCd:this.queryParams.orgCd }).then(response => {
          this.WiFarmerBList = response.rows;
        });
      },
      /** 查询行政区用水日计划列表 */
      getList() {
        this.loading = true;
        this.aloading = true;


        let param = {
          year:this.queryParams.planY,
          orgCd: this.queryParams.orgCd,
        }
        this.tableTitle = this.titleStr
        if(this.radio == 1){
          getAcrePlanByYear(param).then(response => {
            this.wrPlanDayAdList = response.rows;
            let sun = 0
            response.rows.forEach(element => {
              sun += element.planVol
            });
            this.sumPlan = (sun/10000).toFixed(2)
            this.aloading = false;
          });
          listWiOrgplanM(param).then(response => {
            let arr = response.rows.map((element,index) => {
              return {
                ...element,
                xEdit:false,
              }
            });
            this.wrPlanRiunList = arr;
            this.loading = false;
          });
        }else{
          getWiLandBListByFarmCd({
            year:this.queryParams.planY,
            farmCd: this.queryParams.farmCd,
          }).then(response => {
              this.wrPlanDayAdList = response.rows;
              let sun = 0
              response.rows.forEach(element => {
                sun += element.planVol
              });
              this.sumPlan = (sun/10000).toFixed(2)
              this.aloading = false;
            });
            listWiFarmplanM({
              year:this.queryParams.planY,
              farmCd: this.queryParams.farmCd,
            }).then(response => {
              let arr = response.rows.map((element,index) => {
                return {
                  ...element,
                  xEdit:false,
                }
              });
              this.wrPlanRiunList = arr;
              this.loading = false;
            });
        }

      },
      //编辑功能
      handleUpdate(index, row){
        let isck = false;
        this.wrPlanRiunList.forEach((item, index) => {
          if(item.xEdit){
            isck = item.xEdit;
            return;
          }
        });
        if(isck){
          this.$message({
            showClose: true,
            message: '请保存已编辑内容！！！',
            type: 'error'
          });
          return;
        }

        this.wrPlanRiunList = this.wrPlanRiunList.map((item, i) => {
          if (index === i) {
            item.xEdit = true;
          }
          return item
        })
      },
      //编辑保存
      handlesave(index, row){
        let param = {
          ...row,
          year:this.queryParams.planY,
          orgCd:this.queryParams.orgCd,
        }
        param.monPlan = parseFloat(param.firstPlan)  + parseFloat(param.secondPlan) +  parseFloat(param.thirdPlan)
        updateWiOrgplanM(param).then(response => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          this.getList();
        });
      },
      // 撤销功能
      handleQuit(index, row) {
        this.wrPlanRiunList = this.wrPlanRiunList.map((item, i) => {
          if (index === i) {
            item.xEdit = false;
          }
          return item
        })
        this.getList();
      },
      handleClick(type){
         if(type == 1){
          this.$confirm('此操作将覆盖当前数据, 是否继续导入上一年数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.wrPlanRiunList = []
            if(this.radio == 1){
              importLastYearOrgPlan({
                year:this.queryParams.planY - 1,
                orgCd: this.queryParams.orgCd,
              }).then(res => {
                this.getList();
                this.$message({
                  type: 'success',
                  message: '导入成功!'
                });
              })
            }else{
              if(this.queryParams.farmCd == null){
                this.$message({
                  type: 'warning',
                  message: '请选择农户!'
                });
                return
              }
              importLastYearFarmPlan({
                year:this.queryParams.planY - 1,
                farmCd: this.queryParams.farmCd,
              }).then(res => {
                this.getList();
                this.$message({
                  type: 'success',
                  message: '导入成功!'
                });
              })

            }


          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消导入'
            });
          });
         }else if(type == 2){
          this.$confirm('此操作将重新计算当前数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.wrPlanRiunList = []
            if(this.radio == 1){
              OrgcalcTenPlan({
                year:this.queryParams.planY,
                orgCd: this.queryParams.orgCd,
              }).then(res => {
                if(res.code == 200){
                  this.getList()
                  this.$message({
                    type: 'success',
                    message: '重新计算成功!'
                  });
                }
              })

            }else{
              if(this.queryParams.farmCd == null){
                this.$message({
                  type: 'warning',
                  message: '请选择农户!'
                });
                return
              }
              FarmcalcTenPlan({
                year:this.queryParams.planY,
                farmCd: this.queryParams.farmCd,
              }).then(res => {
                if(res.code == 200){
                  this.getList()
                  this.$message({
                    type: 'success',
                    message: '重新计算成功!'
                  });
                }
              })
            }

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取重新计算'
            });
          });

         }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 导出按钮操作 */
      handleExport() {
        this.queryParams.tableTitle = this.tableTitle;
        var code = this.queryParams.orgCd;
        var char = code.substring(6, 9);
        if ('000' == char) {
          this.download('distribute/distribute/wrPlanDayAd/export', {
            ...this.queryParams
          }, this.tableTitle + `.xlsx`)
        } else {
          this.download('distribute/distribute/wrPlanDayRiun/export', {
            ...this.queryParams
          }, this.tableTitle + `.xlsx`)
        }
      },

      /** 查询行政区域下拉树结构 */
      getTreeselect() {
        organtreeList({}).then((response) => {
          response.data.forEach(element => {
            if(element.orgLevel == 2 || element.orgLevel == 3  ){
              element.isDisabled = false
            }
          });
          this.xzqhOptions = this.handleTree(response.data, "orgCd", "parentOrgCd");
          console.log(this.xzqhOptions)
        });
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.orgCd,
          label: node.orgNm,
          children: node.children,
        };
      },

    }
  };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

    .tb_title{
        // width: 430px;
        text-align: center;
        margin: 5px auto;
        margin-bottom: 15px;
        font-weight: 700;
    }

    .tb_dw{
        font-size: 13px;
        position: absolute;
        top: 84px;
        right: 40px;
    }

    .tb_left{
        font-size: 13px;
        position: absolute;
        top: 84px;
        left: 40px;
    }

    .hj_cl{
        font-weight: 700;
    }

    .hj_cl_blue {
        color: #1890ff !important;
        font-weight: 700;
    }

    .el-table__footer-wrapper tbody td.el-table__cell{
        font-weight: 700;
    }
    .el-table .el-table__footer-wrapper .cell{
        font-weight: 700;
    }

    .vue-treeselect__placeholder, .vue-treeselect__single-value {
        line-height: 30px;
    }

    .vue-treeselect {
        width: 300px;
        height: 30px;
        .vue-treeselect__control {
            height: 30px;
            .el-form-item--medium .el-form-item__content {
                line-height: 30px;
                .vue-treeselect__placeholder, .vue-treeselect__single-value {
                    line-height: 30px;
                }
            }
        }
    }

    .el-table th.gutter{
        display: table-cell!important;
    }

</style>

